/**
 * Created by tdzl2003 on 10/16/16.
 */

import {
  CompositeDecorator,
  Entity,
} from 'draft-js';
import './hookBlockTreeRenderer';
import {get} from '../../logics/rpc';

function findLinkEntities(contentBlock, callback) {
  contentBlock.findEntityRanges(
    (character) => {
      const entityKey = character.getEntity();
      return (
        entityKey !== null &&
        Entity.get(entityKey).getType() === 'LINK'
      );
    },
    callback
  );
}

const Link = (props) => {
  const {href} = Entity.get(props.entityKey).getData();
  return (
    <a href={href}>
      {props.children}
    </a>
  );
};

function handleStrategy(contentBlock, callback) {
  contentBlock.findEntityRanges(
    meta=>{
      const entity = meta.getEntity();
      return (
        entity !== null &&
        Entity.get(entity).getType() === 'IMAGE'
      );
    },
    (start, end) => {
      callback(start, end);
    },
  );
}

class Image extends React.Component {
  static isAtomic = true;
  state = {
    src: null,
  }
  componentWillMount(){
    this.loadImage(this.props);
  }
  componentWillReceiveProps(newProps){
    this.loadImage(newProps);
  }
  async loadImage(props){
    const entity = Entity.get(props.entityKey).getData();
    const w = entity.get('w');
    const h = entity.get('h');
    const key = entity.get('key');
    if (!key) {
      return;
    }
    const {url} = await get('/admin/download', {key});
    this.setState({
      src: url,
      w, h,
    });
  }

  render() {
    const {offsetKey} = this.props;
    const {src, w, h} = this.state;
    if (!src) {
      return (
        <img alt="[上传中]" data-offset-key={offsetKey} ref={v=>{
          if (v) {
            v.textContent = ' ';
          }
        }}
             data-text="true"
        />
      );
    }
    return (
      <img style={{width: w, height:h}} src={src} alt="[图片]" data-offset-key={offsetKey} ref={v=>{
        if (v) {
          v.textContent = ' ';
        }
      }}
           data-text="true"
      />
    );
  }
}


export default new CompositeDecorator([
  {
    strategy: findLinkEntities,
    component: Link,
  },
  {
    strategy: handleStrategy,
    component: Image,
  },
]);
